/// ===========================================================================
/// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
/// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
/// PURPOSE.
/// ===========================================================================
/// 
/// Project:        MOSS Usage Tools
/// Authors:        Leonid Lyublinski (leonidly@microsoft.com)
///                 Rita Zhang (ritazh@microsoft.com)
/// Company:        Microsoft Services
/// Date:           05/04/2008  
/// Version:        1.0
///
/// ===========================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
//using Microsoft.Office.Interop.Excel;

namespace Microsoft.SharePoint.Administration.UsageSettings
{
    /// <summary>
    /// The page is responsible for the timer job settings
    /// </summary>
    public class EditUsageLogProcessorPage : LayoutsPageBase
    {
        #region Controls
        protected Literal LiteralPageTitle;
        protected Literal LiteralMain;
        protected System.Web.UI.WebControls.CheckBox CbUPTimerJobEnabled;
        protected DropDownList ScheduleDropDown;
        protected System.Web.UI.WebControls.Button SubmitButton;
        protected System.Web.UI.WebControls.Button CancelButton;
        protected System.Web.UI.WebControls.TextBox CSVLogDirectory;
        
        #endregion

        #region Private Fields
        private const string CUSTOM_TIMER_JOB_NAME = "Usage Log Processor Timer Job";

        #endregion

        #region Page Events

        
        protected override void OnLoad(EventArgs e)
        {
            this.Web.AllowUnsafeUpdates = true;
            this.Site.AllowUnsafeUpdates = true;

            //this.CbUPTimerJobEnabled.Load += new EventHandler(CbUPTimerJobEnabled_Load);
            this.CbUPTimerJobEnabled.CheckedChanged += new EventHandler(CbUPTimerJobEnabled_CheckedChanged);
            //this.ScheduleDropDown.SelectedIndexChanged += new EventHandler(ScheduleDropDown_SelectedIndexChanged);
            this.SubmitButton.Click += new EventHandler(SubmitButton_Clicked);
            this.CancelButton.Click += new EventHandler(CancelButton_Clicked);

            if (!this.IsPostBack)
            {
                string defaultDirectory = null;
                defaultDirectory = SPWebService.AdministrationService.UsageSettings.LogFilesDirectory;
                if (defaultDirectory != null)
                {
                    this.CSVLogDirectory.Text = defaultDirectory + @"\Usage";
                    Directory.CreateDirectory(CSVLogDirectory.Text);
                }
            }

        }
        #endregion

        #region Controls Events
        private void CancelButton_Clicked(object sender, EventArgs e)
        {
            this.Web.AllowUnsafeUpdates = true;
            this.Site.AllowUnsafeUpdates = true;

            Response.Redirect("~/_admin/LogUsage.aspx");
        }

        private void SubmitButton_Clicked(object sender, EventArgs e)
        {
            this.Web.AllowUnsafeUpdates = true;
            this.Site.AllowUnsafeUpdates = true;

            try
            {
                foreach (SPJobDefinition job in SPFarm.Local.TimerService.JobDefinitions)
                {
                    if (job.Name == CUSTOM_TIMER_JOB_NAME)
                    {

                        job.IsDisabled = !this.CbUPTimerJobEnabled.Checked;

                        if (!job.IsDisabled)
                        {

                            switch (this.ScheduleDropDown.SelectedItem.Value)
                            {
                                case "1":
                                    SPMinuteSchedule minSchedule = new SPMinuteSchedule();
                                    minSchedule.BeginSecond = 0;
                                    minSchedule.EndSecond = 59;
                                    minSchedule.Interval = 1;
                                    job.Schedule = minSchedule;
                                    break;
                                case "2":
                                    SPHourlySchedule hrSchedule = new SPHourlySchedule();
                                    hrSchedule.BeginMinute = 0;
                                    hrSchedule.EndMinute = 59;
                                    job.Schedule = hrSchedule;
                                    break;
                                case "3":
                                    SPDailySchedule dailySchedule = new SPDailySchedule();
                                    dailySchedule.BeginHour = 0;
                                    dailySchedule.BeginMinute = 0;
                                    dailySchedule.BeginSecond = 0;
                                    dailySchedule.EndSecond = 59;
                                    dailySchedule.EndMinute = 59;
                                    dailySchedule.EndHour = 23;
                                    job.Schedule = dailySchedule;
                                    break;
                                case "4":
                                    SPWeeklySchedule wkSchedule = new SPWeeklySchedule();
                                    wkSchedule.BeginDayOfWeek = DayOfWeek.Monday;
                                    wkSchedule.EndDayOfWeek = DayOfWeek.Sunday;
                                    wkSchedule.BeginHour = 0;
                                    wkSchedule.BeginMinute = 0;
                                    wkSchedule.BeginSecond = 0;
                                    wkSchedule.EndSecond = 59;
                                    wkSchedule.EndMinute = 59;
                                    wkSchedule.EndHour = 23;
                                    job.Schedule = wkSchedule;
                                    break;
                                case "5":
                                    SPMonthlySchedule monthSchedule = new SPMonthlySchedule();
                                    monthSchedule.BeginDay = 0;
                                    monthSchedule.EndDay = 28;
                                    monthSchedule.BeginHour = 0;
                                    monthSchedule.BeginMinute = 0;
                                    monthSchedule.BeginSecond = 0;
                                    monthSchedule.EndSecond = 59;
                                    monthSchedule.EndMinute = 59;
                                    monthSchedule.EndHour = 23;
                                    job.Schedule = monthSchedule;
                                    break;
                                default:
                                    throw new ApplicationException("EditUsageLogProcessorPage an error has occurred.");



                            }
                            string csvFileLocation = null;
                            csvFileLocation = this.CSVLogDirectory.Text;

                            if (csvFileLocation != null && csvFileLocation != string.Empty)
                            {
                                if (!job.Properties.ContainsKey("UsageLogProcessorProperties"))
                                {
                                    job.Properties.Add("UsageLogProcessorProperties", this.CSVLogDirectory.Text);
                                }
                                else
                                {
                                    job.Properties["UsageLogProcessorProperties"] = this.CSVLogDirectory.Text;
                                }


                                //this.UpdateConnection("logs.csv", Path.Combine(this.CSVLogDirectory.Text, @"Default.xlsx"), Path.Combine(this.CSVLogDirectory.Text, "new.xlsx"));
                            }
                        }

                        
                        job.Update();
                    }
                }
            }
            catch (Exception x)
            {

            }
            finally
            {
                Response.Redirect("~/_admin/LogUsage.aspx");
            }

        }

        
        private void CbUPTimerJobEnabled_CheckedChanged(object sender, EventArgs e)
        {
            this.Web.AllowUnsafeUpdates = true;
            this.Site.AllowUnsafeUpdates = true;

            if (this.CbUPTimerJobEnabled.Checked)
            {
                this.ScheduleDropDown.Focus();
                this.ScheduleDropDown.Enabled = true;
                this.CSVLogDirectory.Focus();
                this.CSVLogDirectory.Enabled = true;
            }
            else
            {
                this.ScheduleDropDown.Enabled = false;
                this.CSVLogDirectory.Enabled = false;
            }
        }
        #endregion

        #region Utilties

        #region Future release
        public string BuildConnection(string folderPath)
        {

            StringBuilder builder = new StringBuilder();

            builder.Append("ODBC;DBQ=");

            builder.Append(folderPath);

            builder.Append(";DefaultDir=");

            builder.Append(folderPath);

            builder.Append(";Driver={Microsoft Access Text Driver (*.txt, *.csv)};DriverId=27;Extensions=None,asc,csv,tab,txt;FIL=text;MaxBufferSize=2048;MaxScanRows=25;PageTimeout=5;SafeTransactions=0;Threads=3;UserCommitSync=Yes;");



            return builder.ToString();

        }

        
        //public void UpdateConnection(string csvName, string sourcePath, string destinationPath)
        //{

        //    try
        //    {

        //        if (File.Exists(Path.Combine(Path.GetDirectoryName(sourcePath), csvName)))
        //        {

        //            ApplicationClass excelApplication = new ApplicationClass();

        //            object paramMissing = Type.Missing;

        //            Workbook book = excelApplication.Workbooks.Open(sourcePath,

        //                paramMissing, paramMissing, paramMissing, paramMissing,

        //                paramMissing, paramMissing, paramMissing, paramMissing,

        //                paramMissing, paramMissing, paramMissing, paramMissing,

        //                paramMissing, paramMissing);

        //            PivotCaches caches = book.PivotCaches();

        //            PivotCache cache = caches[1];

        //            string connection = BuildConnection(Path.GetDirectoryName(sourcePath));

        //            cache.Connection = connection;

        //            // update SQL statement

        //            cache.CommandText = "select * from " + csvName;



        //            book.SaveCopyAs(destinationPath);

        //        }

        //        else throw new FileNotFoundException(Path.Combine(sourcePath, csvName) + " not found");

        //    }

        //    catch (Exception ex)
        //    {

        //        logMessage("EditUsageLogProcessor -- " + ex.StackTrace, EventLogEntryType.Error);

        //    }

        //}

        #endregion
        private static void logMessage(string message, EventLogEntryType type)
        {
            
            if (!EventLog.SourceExists(Common.Resource.AppLogName))
                EventLog.CreateEventSource(Common.Resource.AppLogName, "Application");
            EventLog.WriteEntry(Common.Resource.AppLogName, message, type);
            

        }
        #endregion



    }
}
